package com.assistant.core.modules.sys.adapter;

import com.assistant.core.modules.sys.BusinessContext;
import com.assistant.core.modules.sys.domain.user.User;
import com.assistant.exception.AssistantException;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 操作用户参数自动注入，如果控制器方法的入参中有User，则会自动赋值位当前操作用户
 */
public class OperatorHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return User.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        final Class<?> parameterType = parameter.getParameterType();
        final User operator = BusinessContext.getOperator();
        if (operator == null) {
            throw new AssistantException("没有登录");
        }
        if (!parameterType.isAssignableFrom(operator.getClass())) {
            throw new IllegalArgumentException("实际操作人类型为" + operator.getClass().getSimpleName() + ", 不能用" + parameterType.getSimpleName() + "接收!");
        }
        return operator;
    }
}
